-- Serialization and deserialization of tables into strings

local lower = string.lower
local find = string.find
local sub = string.sub

--------------------------------------------------------------------------------

local params
local function SerializeTable (tableName, tableValue)
  for k, v in pairs(tableValue) do
    local key = tableName .. "." .. k
    if (type(v) == "table") then
      SerializeTable (key, v)
    else
      params[key] = (type(v) == "boolean") and tostring(v) or v
    end
  end
end
  
  
function SerializeCustomParams (defsTable)  
  for _, def in pairs(defsTable) do
    params = def.customparams
    --printTable ("defsTable["..tableName.."].paramsBefore", params)
     
    for k, v in pairs(params) do
      --convert all tables to strings
      if (type(v) == "table") then
        SerializeTable (k, v)
        params[k] = nil  
      elseif (type(v) == "boolean") then
        params[k] = tostring(v)
      end      
       
      --convert all CustomParams to strings  --not needed         
      -- if (type(v) ~= "string") then
        -- params[k] = tostring(v)
      -- end
    end
    
    --printTable ("defsTable["..tableName.."].paramsAfter", params)  
  end
end 


local stringToBoolean = {
  ["true" ] = { true , },
  ["false"] = { false, },
}

local upcaseParams
local function DeserializeParams (params)
  local myParams = {}
  for k, v in pairs(params) do
    local t = myParams
    local lastPos = 1
    local pos = find(k, ".", lastPos, true)
    
    while (pos) do
      local key = sub(k, lastPos, pos - 1)
      key = tonumber(key) or upcaseParams[key] or key
      if (type(t[key]) ~= "table") then
        t[key] = {}
      end
      t = t[key]
      
      lastPos = pos + 1
      pos = find(k, ".", lastPos, true)
    end
    
    -- if (lastPos > 1) then
      local key = sub(k, lastPos)
      key = tonumber(key) or upcaseParams[key] or key
      t[key] = tonumber(v) or (stringToBoolean[v] and stringToBoolean[v][1] or v)
      -- params[k] = nil      
    -- end
  end
  return myParams
end


function DeserializeCustomParams (defsTable, _upcaseParams)
  upcaseParams = {}
  for _, name in ipairs(_upcaseParams) do
    upcaseParams[lower(name)] = name
  end

  for _, def in ipairs(defsTable) do
    def.myCustomParams = DeserializeParams (def.customParams)
    --ud.customParams.TROLOLOLO = 3 -- doesn't work
    --ud.TROLOLOLO = 3 -- works
  end
end

-------------------------------------------------------------------------------- 